package com.fantesy.jwtdemo.filter;

import com.fantesy.jwtdemo.util.JWTTokenUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author fantsey
 * @date 2020/2/27
 */
public class TokenFilter implements Filter {


    private static String[] unNedLoginURI = {"/static", "/getToken", "/test3"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        System.out.println(sessionId);
        String uri = request.getRequestURI();
        if (!checkUnNeedToken(uri)){
            // 从session中获取token
            //String token = (String)session.getAttribute("token");

            // 获取前端传回的token
            String token = request.getHeader("token");

            if (token == null || token.isEmpty()){
                throw new RuntimeException("token不准确！禁止访问");
            }
            Claims claims = null;
            try {
                claims = JWTTokenUtils.parseClaims(token);
            } catch (Exception e) {
                throw new RuntimeException("token不准确！禁止访问");
            }
            String username = (String)claims.get("username");
            String password = (String)claims.get("password");
            if ("van".equalsIgnoreCase(username) && "123456".equalsIgnoreCase(password)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                throw new RuntimeException("token不准确！禁止访问");
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }

    public static boolean checkUnNeedToken(String uri){
        boolean flag = false;
        if (unNedLoginURI != null){
            for (int i = 0; i < unNedLoginURI.length; i++) {
                if (uri.startsWith(unNedLoginURI[i])) {
                    flag = true;
                }
            }
        }
        return flag;
    }
}
